<?php

namespace app\admin\controller;
use app\base\controller\Base;
use think\Request;
use think\Cache;
use think\Config;
use think\Session;


class OrderDetails extends Base
{
    public  $model;

    public function __construct()
    {
   $this->model = model("OrderDetails");
        parent::__construct();

    }

    /**
     * @return \think\response\Json  开仓委托
     */
    public function index()
    {//
        //搜索条件 时间 用户号码 状态
        $where['a.status'] =['in','0,1'];
        return $this->baseXIndex($where);

    }

    /**
     * @return \think\response\Json 平仓记录
     */
    public function ping()
 {//
     //开仓
     $where['a.status'] =['in','2'];
     $where['a.is_sell_status'] =['in','1,2'];
     return $this->baseXIndex($where);

 }

    /**
     * @return \think\response\Json 持仓列表
     */
    public function position()
    {//

        //开仓
        $where['a.status'] =['in','2'];

        return $this->baseXIndex($where);

    }

    /**
     * @return \think\response\Json 废单记录
     */
    public function waste()
    {//
        //开仓
        $where['status'] = 1;
        $OrderDetailsRecordModel = new \app\admin\model\OrderDetailsRecord();

        if(isset($this->mobile)){
            $where['a.mobile']=['like','%'.$this->mobile.'%'];
        }
        if(isset($this->start_time)||isset($this->end_time))
        {
            if(isset($this->start_time)&&isset($this->end_time)&&($this->start_time==$this->end_time)){
                $t = 60*60*24-1;
                $this->end_time = $this->start_time;
                $where['a.created_at']=['between',[strtotime($this->start_time),strtotime($this->end_time)+$t]];
            }else{
                $where['a.created_at']=['between',[isset($this->start_time)?strtotime($this->start_time):strtotime("1970/1/1"),isset($this->end_time)?strtotime($this->end_time):strtotime("3030/11/1")]];
            }


        }

        if(isset($this->direction)){
            $where['a.direction']=$this->direction;
        }
        if(isset($this->ordersn)){
            $where['a.ordersn']=$this->ordersn;
        }


        $res =   $OrderDetailsRecordModel->defaultPage($where);






        if(empty($res)){
            return failJson("暂无交易记录");
        }
        return   resJson(1,"查询成功",$res['res'],$res['pageInfo']);
    }


    /**
     *  交易记录
     */
    public function transaction(){
       // $model = new
        $where['a.status'] = 0;
        $OrderDetailsRecordModel = new \app\admin\model\OrderDetailsRecord();
        if(isset($this->mobile)){
            $where['a.mobile']=['like','%'.$this->mobile.'%'];
        }
        if(isset($this->direction)){
            $where['a.direction']=$this->direction;
        }

        if(isset($this->ordersn)){
            $where['a.ordersn']=$this->ordersn;
        }
        if(isset($this->start_time)||isset($this->end_time))
        {
            if(isset($this->start_time)&&isset($this->end_time)&&($this->start_time==$this->end_time)){
                $t = 60*60*24-1;
                $this->end_time = $this->start_time;
                $where['a.created_at']=['between',[strtotime($this->start_time),strtotime($this->end_time)+$t]];
            }else{
                $where['a.created_at']=['between',[isset($this->start_time)?strtotime($this->start_time):strtotime("1970/1/1"),isset($this->end_time)?strtotime($this->end_time):strtotime("3030/11/1")]];
            }


        }
        w_s("lay",1);
        $res =   $OrderDetailsRecordModel->defaultPage($where,[false,true]);

        if(empty($res)){
            return failJson("暂无交易记录");
        }
        return   resJson(1,"查询成功",$res['res'],$res['pageInfo']);



    }


 private function baseXIndex($where=[]){

     if(isset($this->mobile)){
         $where['u.mobile']=['like','%'.$this->mobile.'%'];
     }
     $t = 60*60*24-1;
     if(isset($this->start_time)||isset($this->end_time))
     {
         if(isset($this->start_time)&&isset($this->end_time)&&($this->start_time==$this->end_time)){

             $this->end_time = $this->start_time;
             $where['a.created_at']=['between',[strtotime($this->start_time),strtotime($this->end_time)+$t]];
         }else{
             $where['a.created_at']=['between',[isset($this->start_time)?strtotime($this->start_time):strtotime("1970/1/1"),isset($this->end_time)?strtotime($this->end_time)+$t:strtotime("3030/11/1")]];
         }


     }
     if(isset($this->ordersn)){
         $where['a.ordersn']=$this->ordersn;
     }

     if(isset($this->status)){
         $where['a.status']=$this->status;
     }
     //时间的处理
     $res = $this->model->OrderDetails_page($where);

     return   resJson(1,$this->ecLang("query"),$res['res'],$res['pageInfo']);
 }



 public function bohui(){
     //'is_sell_status';
     $orderDetails = $this->model->where("id",$this->id)->find();
     if($orderDetails['is_sell_status']!=2){
         return failJson("该订单不在驳回状态队列中..");
     }
     $res = $orderDetails->save(['is_sell_status'=>0],['id'=>$this->id]);
     if(empty($res)){
          return  failJson("驳回失败");
     }
     return  sucessJson("该订单已被驳回");
 }



 //未审核到审核中
 public function audit(){
         //改变状态
        $orderDetails = $this->model->where("id",$this->id)->find();
        if($orderDetails['status']==0){
           $status =  $this->model->save(['status'=>1],['id'=>$this->id]);
           if($status){

               return   sucessJson($this->ecLang("sucessstatus"));//审核中
           }else{
               return   failJson($this->ecLang("failtatus"));//审核中
           }
        }else{
            return   failJson($this->ecLang("error"));//异常
        }
 }

 //审核中到持仓中
 public function delegation(){

     $t = time();
     if($this->Initial_price<=0){
         return failJson("期初价格不能为空");
     }

     $data = [
         "option_code"=>$this->option_code, //q股权编号
         "Initial_price"=>$this->Initial_price,//期初价格
         "equity_nums"=>$this->equity_nums,//股数
         "closing_time"=>$t,
         "buy_time"=>$t,
         "buy_money"=>$this->totalAssets,
          "manage_per"=>$this->manage_per,//管理率
          "money_value_date"=>strtotime($this->money_value_date),//起息日
          "money_expiry_date"=>strtotime($this->money_expiry_date),//到日期
     ];





     if(isset($this->remark)){
         $data['remark'] = $this->remark;
     }
       $res =  $this->model->delwithData($data,$this->id);

     if($res['status']){

         $OrderDetails= new \app\np\model\OrderDetails;//订单详情
         $orderDe =  $OrderDetails->where("id",$this->id)->find();
         $users =  new \app\out\model\Users;
         $userlist =  $users->where(['id'=>$orderDe['user_id']])->find();
         $Share= new \app\np\model\Shares;//订单详情
         $Sharelist = $Share->where(['id'=>$orderDe['stock_id']])->find();
         //买入操作
         sedMessageAll($userlist['mobile'],"buy",$Sharelist['code']);

         return   sucessJson("订单进入持仓");//审核中
     }else{

         return   failJson("订单在审核失败");//审核中
     }
 }



 //  订单改变状态 卖出申请未审核 到审核中
 public function  abolish(){
     $orderDetails = $this->model->where("id",$this->id)->find();
     if($orderDetails['is_sell_status']!=1){

         return   failJson("订单卖出申请失败");//审核中
     }
     //更新状态为2
   $status =   $this->model->where("id",$this->id)->update(["is_sell_status"=>2]);
     if($status){

         return   sucessJson("订单卖出申请成功");//审核中
     }else{

         return   failJson("订单卖出申请失败");//审核中
     }
 }


 //审核中到卖出
public function selllast(){
     $orderDetails = $this->model->where("id",$this->id)->find();
     if($orderDetails['is_sell_status']!=2){

         return   failJson("订单卖出失败");//审核中
     }
     $rose = bcdiv(bcsub($this->exercise_price,$orderDetails['Initial_price'],2),$orderDetails['Initial_price'],5);

     $Profit = bcmul($orderDetails['capital_money'],$rose,2);
    /**
     *  盈亏3W
     */
        $data = ["direction"=>0,"is_sell_status"=>3,"status"=>3,"exercise_price"=>$this->exercise_price,"sell_money"=>$Profit,"sell_time"=>time()];

       $status =    $this->model->changeSell($data,$this->id,$orderDetails);
        if($status){
            //卖出成功
            $users =  new \app\out\model\Users;
            $userlist =  $users->where(['id'=>$orderDetails['user_id']])->find();
            $Share= new \app\np\model\Shares;//订单详情
            $Sharelist = $Share->where(['id'=>$orderDetails['stock_id']])->find();
            sedMessageAll($userlist['mobile'],"sell",$Sharelist['code']);

            return   sucessJson("订单卖出成功");//审核中
        }else{
            //卖出失败
            return   failJson("订单卖出失败");//审核中
        }

    }




    //撤单  订单改为废单
    public function revokeapply(){

        $order = $this->model->where(['id'=>$this->order_id])->find();
        /*  if($order['status']==0){
              return   failJson("该订单未进入审核,不能撤单");//审核中
              //0未审核 1审核中  2持仓中 3卖出 4废单
          }*/
        if(empty($order)){
            return   failJson("该订单不存在");//审核中
        }
        if($order['status']==4){
            return   failJson("该订单已撤单");//审核中
        }

        if($order['status']==2){
            return   failJson("该订单已在持仓中");//审核中
        }

        if($order['status']==3){
            return   failJson("该订单已卖出");//审核中
        }

        $status =  $this->model->revokeapply($this->order_id,$this->user_id);//撤单申请
        // $status =  $this->model->save(['status'=>4],['id'=>$this->id,"user_id"=>$this->sid_user_id]);
        if($status['status']){
            //冻结金额返回



            admin_logs(["admin_user_id"=>$this->admin_user_id,"name"=>"订单","content"=>"废单成功"]);
            return   sucessJson($status['msg']);//审核中
        }else{
            admin_logs(["admin_user_id"=>$this->admin_user_id,"name"=>"订单","content"=>"废单失败"]);
            return   failJson($status['msg']);//审核中
        }

    }


    /**
     *      持仓中改变期初价格
     */
    public function changebeginning(){
        $order = $this->model->where(['id'=>$this->order_id])->find();
        if(empty($order)){
            return   failJson("暂无该订单");//审核中
        }
        if($this->Initial_price<=0){
            return failJson("期初价格不能为空");
        }

        if($order['status']!=2){
            return   failJson("暂不能修改期初价格");//审核中
        }
        $res = $this->model->where("id",$this->order_id)->update(['Initial_price'=>$this->Initial_price]);
        if(empty($res)){
            return failJson("修改期初价格失败");
        }
        addMessage($order['user_id'],"订单:{$order['ordersn']} 修改期初价格成功");
        return sucessJson("修改期初价格成功");




    }







}
